package service

import (
	"awesomeProject/app/model"
	"awesomeProject/app/request"
	"awesomeProject/app/response"
	"awesomeProject/global"
	"awesomeProject/util"
	"context"
	"github.com/shopspring/decimal"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"strings"
	"time"
)

type ItemFlowRankSrv struct{}

// ItemFlowRank 商品流量排行
func (i *ItemFlowRankSrv) ItemFlowRank(req request.ItemFlowRank) response.Resp {
	filter := bson.D{{"shop_id", req.ShopId}}
	if req.DateVal != "" {
		if req.DateType == 1 || req.DateType == 4 { // 日期
			filterDate, _ := time.Parse("2006-01-02", req.DateVal)
			filter = append(filter, bson.E{Key: "date", Value: filterDate})
		} else if req.DateType == 2 || req.DateType == 3 { // 近7天or近30天
			dateRange := strings.Split(req.DateVal, "~")
			sDate, _ := time.Parse("2006-01-02", dateRange[0])
			eDate, _ := time.Parse("2006-01-02", dateRange[1])
			filter = append(filter, bson.E{Key: "date", Value: bson.M{"$gte": sDate, "$lte": eDate}})
		} else if req.DateType == 5 { // 月份
			month, _ := time.Parse("2006-01", req.DateVal)
			sd := util.GetMonthStartAndEnd(month.Year(), int(month.Month()))
			filter = append(filter, bson.E{Key: "date", Value: bson.M{"$gte": sd["start"], "$lte": sd["end"]}})
		}
	}

	var result []model.ItemFlowRank
	match := bson.D{{
		"$match", filter,
	}}
	group := bson.D{{
		"$group", bson.D{
			{"_id", bson.D{{"shop_id", bson.M{"$toInt": "$shop_id"}}, {"item_id", bson.M{"$toInt": "$item_id"}}}},
			{"date", bson.M{"$last": "$date"}},
			{"item_no", bson.M{"$last": "$item_no"}},
			{"item_name", bson.M{"$last": "$item_name"}},
			{"image", bson.M{"$last": "$image"}},
			//{"ctm_order_view_rate", bson.M{"$last": decimal.NewFromInt(0)}},
			{"ctm_item_click_uv", bson.M{"$sum": bson.M{"$toInt": "$ctm_item_click_uv"}}},
			{"item_cart_uv", bson.M{"$sum": bson.M{"$toInt": "$item_cart_uv"}}},
			{"order_uv", bson.M{"$sum": bson.M{"$toInt": "$order_uv"}}},
			{"item_verified_cnt", bson.M{"$sum": bson.M{"$toInt": "$item_verified_cnt"}}},
			//{"ctm_item_view_rate_new", bson.M{"$sum": bson.M{"$toDouble": bson.M{"$replaceAll": bson.M{ "input": "$ctm_item_view_rate_new", "find": "%", "replacement": "" }}}}},
		},
	}}
	sort := bson.D{{"$sort", bson.M{"ctm_item_click_uv": -1, "ctm_item_click_cnt": -1}}}
	limit := bson.D{{"$limit", 10}}
	cursor, err := global.MongoDB.Collection("item_flow_rank").Aggregate(context.TODO(), mongo.Pipeline{match, group, sort, limit})
	if err != nil {
		return response.ErrQuery
	}
	if err = cursor.All(context.TODO(), &result); err != nil {
		return response.ErrQuery
	}
	for i, ifr := range result {
		if ifr.CtmItemClickUv != 0 {
			result[i].CtmOrderViewRate = decimal.NewFromInt(int64(ifr.OrderUv)).Div(decimal.NewFromInt(int64(ifr.CtmItemClickUv)))
		} else {
			result[i].CtmOrderViewRate = decimal.NewFromInt(1)
		}
	}
	return response.OK.WithData(result)
}
